﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = "List";
}
@Styles.Render("~/content/fineuploader/fineuploader-3.5.0.css")
@Scripts.Render("~/content/fineuploader/fineuploader-3.5.0.js")
@Scripts.Render("~/content/fineuploader/iframe.xss.response-3.5.0.js")
<style>
    .statuses_list {
        background-color: #F5F5F5;
        border: 1px solid #DDDDDD;
         /*width: 500px;*/
         padding-bottom: 10px;
    }

    .columnpic
    {
        background-color: #FFFFFF;
        border: 1px solid #DDDDDD;
        border-radius: 4px 4px 4px 4px;
        margin: 15px 0;
        position: relative;
    }

    .column
    {
        background-color: #FFFFFF;
        border: 1px solid #DDDDDD;
        border-radius: 4px 4px 4px 4px;
        margin: 15px 0;
        padding: 10px 10px;
        position: relative;
    }
    .row-fluid {
       
        padding: 0px 14px 0;
    }
    .post {
       background-color: #F5F5F5;
        border: 1px solid #DDDDDD;
         /*width: 500px;*/
        margin-bottom: 15px;
    }
    .post_inner {
        padding-top: 10px;
        padding-bottom: 10px;
       padding-left: 15px;

    }
    .logo {
        float: left;
        margin: 15px 0
    }
   .qq-upload-button {
       width: 200px;
   }
   .operation {
       margin-top: 10px;
   }

</style>
<div class="container">
    
   <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a href="#statusTab" data-toggle="tab">@T("status.tab.title")</a></li>
        <li><a href="#prodTab" data-toggle="tab">@T("prod.tab.title")</a></li>
       
    </ul>
    
<div class="tab-content">
    <div class="post tab-pane active" data-bind="visible:IsOwner" style="display: none" id="statusTab">
         <!-- ko with: CustomerStatusModel-->
        <div  >
            <div class="post_inner">
                <textarea data-bind="value:Text" rows="5" class="span11" placeholder=""></textarea>
                <div>
    
                    <!-- ko foreach: Pics-->
                    <img data-bind="attr:{src: PicUrl}"  /> 
                    <!-- /ko -->
                </div>


                <div class="">
                    <ul id="manualUploadModeExample1" class="unstyled "></ul>
                </div>




               <!-- ko if: $root.IsOwner -->
                <input type="button" value="Post" data-bind="click:PostCustomerStatus,css:{disabled:Text()==''}"  class="btn btn-primary"/>
                <!-- /ko -->
            </div>
       
         
        </div>
        
        <!-- /ko -->
    </div>
    <div class="tab-pane post" id="prodTab" >
        <!-- ko with: ProductStatusModel-->
        <div class="" >
            <div class="post_inner clickmsg" >
                <textarea data-bind="value:ProductDescription,attr:{placeholder:'@T("product.post.placeholder.title")'}" rows="5" class="span11"></textarea>
                <div>
                    <input type="text" data-bind="value:ProductStock,attr:{placeholder:'@T("productstatus.productstock.title")'}" />
                </div>
                <div>
                    <input type="text" data-bind="value:ProductPrice,attr:{placeholder:'@T("productstatus.productprice.title")'}" />
                </div>
                <div>
    
                    <!-- ko foreach: Pics-->
                    <img data-bind="attr:{src: PicUrl}"  /> 
                    <!-- /ko -->
                </div>

                <div>
                    <ul id="manualUploadModeExample2" class="unstyled "></ul>
                </div>



                <!-- ko if: $root.IsOwner -->
                <input type="button" value="Post" data-bind="click:PostProductStatus,css:{disabled:ProductDescription()==''}"  class="btn btn-primary"/>
                <!-- /ko -->
            </div>
       
         
        </div>
        
        <!-- /ko -->
    </div>
</div>
   
    

    <!-- ko ifnot: IsOwner -->
        <!-- ko ifnot: IsFriend -->
            <input type="button" value="follow" data-bind="click:CreateFriendShip"  class="btn btn-primary"/> 
        <!-- /ko -->
    <!-- /ko -->
    
    <div class="statuses_list" data-bind="visible:Messages().length>0" style="display: none">
    
    

        <!-- ko foreach: Messages-->

        <div class="row-fluid" >
            <div class="logo">

                <img data-bind="attr:{src: CustomerLogoUrl}" /> 
            </div>
            <div class="span9 column clickmsg" data-bind="attr:{link:'/status/' +Id()},click:GoOnePageProduct">
                <p  data-bind="html:Text">
                </p>
                 <!-- ko if: IsProduct-->
                <div>
                    
                    <span data-bind="text:ProductStock"></span>
                    <span data-bind="text:ProductPrice"></span>
                </div>
                 <!-- /ko -->
                <!-- ko foreach: Pics-->
                <img data-bind="attr:{src: PicUrl},click:ShowOriginalPic" /> 
                <!-- /ko -->
                
                
                   <div class="operation">
                    <!-- ko if: IsProduct-->
                    @*<input type="button"  data-bind="value:'@T("status.product.buy.title")', click:GoOnePageProduct"   class="btn btn-primary"/>*@
                    <!-- /ko -->
                </div>	
		
            </div>
           
        
            </div>
        <!-- /ko -->
        <div class="row-fluid" >
            <input type="button" value="More" data-bind="click:MoreStatus,visible:Messages().length>0"  class="btn btn-primary span11"/>
        </div>
    </div>    

</div>
    



@{
    var model = ViewBag.Model;
    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}

@section scripts
{
    <script type="text/javascript" src="~/Scripts/jquery.signalR-1.1.2.js"></script>
    <script type="text/javascript" src="~/signalr/hubs"></script>
    <script>

        var init = @jsonStr;

        var hub = $.connection.statuses;

        function StatusListItemModel(id, createdAt, text, customerId, deleted, customerName, customerLogoUrl, customerEmail, pics, isProduct,productStock, productPrice, productId) {


            var self = this;
            self.Id = ko.observable(id);
            self.Text = ko.observable(text);
            self.CustomerId = ko.observable(customerId);
            self.Deleted = ko.observable(deleted);
            self.CustomerName = ko.observable(customerName);
            self.CustomerLogoUrl = ko.observable(customerLogoUrl);
            self.CustomerEmail = ko.observable(customerEmail);
            self.Pics = ko.observableArray(pics);
            self.IsProduct = ko.observable(isProduct);
            self.ProductStock  = ko.observable(productStock);
            self.ProductPrice  = ko.observable(productPrice);
            self.ProductId= ko.observable(productId);

            self.GoOnePageProduct = function(p,event) {
                var link = "/status/" + p.Id();
                //alert('');

                var target = event.target;
                if (target.nodeName == "IMG") {
                    return false;
                } else {  
                    location.href = link;
                }
            };
        }

        function StatusPictureModel(picId, picUrl) {

            var self = this;
            self.PicId = ko.observable(picId);
            self.PicUrl = ko.observable(picUrl);
            self.IsOrignalSize = ko.observable(false);
            self.PicSize = ko.observable(80);
            
            self.ShowOriginalPic = function() {

                if (self.IsOrignalSize() == true) {
                    self.IsOrignalSize(false);
                    self.PicSize(80);
                    $.ajax({
                        url: "/api/PicApi/GetPicUrl",
                        type: 'post',
                        data: ko.toJSON(self),
                        contentType: 'application/json',
                        success: function(result) {

                            self.PicUrl(result.PicUrl);
                        }
                    });
                } else {
                    self.IsOrignalSize(true);
                    self.PicSize(0);
                    $.ajax({
                        url: "/api/PicApi/GetPicUrl",
                        type: 'post',
                        data: ko.toJSON(self),
                        contentType: 'application/json',
                        success: function(result) {

                            self.PicUrl(result.PicUrl);
                        }
                    });
                }
               
            };
        }

        function PageInfo(customerId, pageIndex, pageSize) {
            var self = this;
            self.CustomerId = ko.observable(customerId);
            self.PageIndex= ko.observable(pageIndex);
            self.PageSize= ko.observable(pageSize);
            self.NextPage = function() {
                return new PageInfo(customerId, pageIndex + 1, pageSize);
            };
        }

        function ProductStatusModel() {
            var self = this;
            self.ProductDescription = ko.observable('');
            self.ProductStock = ko.observable('');
            self.ProductPrice = ko.observable('');
            self.Pics = ko.observableArray();


            
            self.PostProductStatus= function(pv) {
                if (self.ProductDescription() != '') {
                    
                    var message = {
                        Text: self.ProductDescription(),
                        Pics : ko.toJS(self.Pics),
                        ProductStock:self.ProductStock(),
                        ProductPrice:self.ProductPrice(),
                    };

                    hub.server.sendProductStatus(message).fail(function(err) {
                    });
                }
            };
           
        }

        function CustomerStatusModel() {
            var self = this;
            self.Text = ko.observable('');
            self.Pics = ko.observableArray();

            self.PostCustomerStatus = function(pv) {
                if (self.Text() != '') {
                    
                    var message = {
                        Text: self.Text(),
                        Pics : ko.toJS(self.Pics)
                    };

                    hub.server.send(message).fail(function(err) {
                    });
                }
            };
        }

        function HomeTimeLineModel() {

            var self = this;

            self.ProductStatusModel = new ProductStatusModel();

            self.CustomerStatusModel = new CustomerStatusModel();
            
            //self.ClientId = ko.observable();
            self.CustomerId = ko.observable(init.CustomerId);
            self.IsOwner = ko.observable(init.IsOwner);
            self.IsFriend = ko.observable(init.IsFriend);
          

            var tempMessages = $.isEmptyObject(init.StatusList) ? [] : $.map(init.StatusList, function(a) {
                var tempPics = $.isEmptyObject(a.StatusPictures) ? [] : $.map(a.StatusPictures, function(p) {
                    return new StatusPictureModel(p.PicId, p.PicUrl);
                });
                var productStock = a.ProductStatus == null ? "":a.ProductStatus.ProductStock;
                var productPrice = a.ProductStatus == null ? "": a.ProductStatus.ProductPrice;
                var productId= a.ProductStatus == null ? "": a.ProductStatus.ProductId;
                return new StatusListItemModel(a.Id, a.CreatedAt, a.Text, a.CustomerId, a.Deleted, a.CustomerName, a.CustomerLogoUrl, a.CustomerEmail, tempPics, a.IsProductStatus, productStock, productPrice, productId);
            });

            self.Messages = ko.observableArray(tempMessages);
            self.PageInfo = new PageInfo(init.CustomerId, 0, 5);           

          
           
          
                                
            
            self.MoreStatus = function() {


                
                self.PageInfo = self.PageInfo.NextPage();
                $.ajax({
                    url: "/api/StatusApi/HomeLine",
                    type: 'post',
                    async :false,
                    data: ko.toJSON(self.PageInfo),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            var statusList = result.StatusList;
                            
                            $.each(statusList, function(index, a) {
                                var tempPics = $.isEmptyObject(a.StatusPictures) ? [] : $.map(a.StatusPictures, function(p) {
                                    return new StatusPictureModel(p.PicId, p.PicUrl);
                                });
                                
                                var productStock = a.ProductStatus == null ? "":a.ProductStatus.ProductStock;
                                var productPrice = a.ProductStatus == null ? "": a.ProductStatus.ProductPrice;
                                var productId= a.ProductStatus == null ? "": a.ProductStatus.ProductId;
                                vm.Messages.push(new StatusListItemModel(a.Id, a.CreatedAt, a.Text, a.CustomerId, a.Deleted, a.CustomerName, a.CustomerLogoUrl, a.CustomerEmail, tempPics, a.IsProductStatus, productStock, productPrice, productId));
                                
                            });
                            
                        } else {
                            alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };
           
            self.CreateFriendShip = function() {
                $.ajax({
                    url: "/api/FriendShipApi/Create",
                    type: 'post',
                    data: ko.toJSON(self),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            alert("保存成功");
                        } else {
                            alert("保存失败：" + result.Msg);
                        }
                    }
                });
            };

        }

        var vm = new HomeTimeLineModel();


        $(function() {

            hub.client.success = function(a) {

                if (a.Status == "success") {
                    if (a.IsProductStatus) {
                        vm.ProductStatusModel.ProductDescription(''); //clear text
                        vm.ProductStatusModel.Pics([]); //clear pictures
                    } else {
                        vm.CustomerStatusModel.Text(''); //clear text
                        vm.CustomerStatusModel.Pics([]); //clear pictures
                    }
                    
                    $('.qq-upload-success').remove(); //clear success upload picture notes
                }
            };
            hub.client.messageReceived = function(a) {

                var tempPics = $.isEmptyObject(a.StatusPictures) ? [] : $.map(a.StatusPictures, function(p) {
                    return new StatusPictureModel(p.PicId, p.PicUrl);
                });

                var productStock = a.ProductStatus == null ? "":a.ProductStatus.ProductStock;
                var productPrice = a.ProductStatus == null ? "": a.ProductStatus.ProductPrice;
                var productId= a.ProductStatus == null ? "": a.ProductStatus.ProductId;
                vm.Messages.unshift(new StatusListItemModel(a.Id, a.CreatedAt, a.Text, a.CustomerId, a.Deleted, a.CustomerName, a.CustomerLogoUrl, a.CustomerEmail,tempPics,a.IsProductStatus,  productStock, productPrice,productId));
            };

            $.connection.hub.start().done(function() {
            });


            ko.applyBindings(vm);
        });

        function goDetail() {

            
        }

        $(document).ready(function() {

            var errorHandler = function(event, id, fileName, reason) {
                qq.log("id: " + id + ", fileName: " + fileName + ", reason: " + reason);
            };


            var uploader2 = new qq.FineUploader({
                element: $('#manualUploadModeExample1')[0],
                autoUpload: true,
                uploadButtonText: "Select Files",
                request: {
                    endpoint: "/FineUploader/UploadFile",
                    params: { "extraParam1": "true", "picSize": "80" }
                },
                callbacks: {
                    onError: errorHandler,
                    onComplete: function(id, fileName, responseJSON) {
                        if (responseJSON.success) {
                            //vm.PictureId(responseJSON.PictureId);
                            //vm.PictureUrl(responseJSON.PictureUrl);
                            vm.CustomerStatusModel.Pics.push(new StatusPictureModel(responseJSON.OriginalPictureId, responseJSON.NewPictureUrl));
                          
                        }
                    }
                }
            });


            var uploader1= new qq.FineUploader({
                element: $('#manualUploadModeExample2')[0],
                autoUpload: true,
                text: {
                    uploadButton: '@T("ProductStatusUploader.Button.Title")'
                },
                request: {
                    endpoint: "/FineUploader/UploadFile",
                    params: { "extraParam1": "true", "picSize": "80" }
                },
                callbacks: {
                    onError: errorHandler,
                    onComplete: function(id, fileName, responseJSON) {
                        if (responseJSON.success) {
                            //vm.PictureId(responseJSON.PictureId);
                            //vm.PictureUrl(responseJSON.PictureUrl);
                            vm.ProductStatusModel.Pics.push(new StatusPictureModel(responseJSON.OriginalPictureId, responseJSON.NewPictureUrl));
                        }
                    }
                }
            });

          

            //$('.clickmsg').on('mouseover', function(e) {
               
            //    var target = e.target, o = $(this);
            //  //  o.css({ 'backgroundColor': '#efefef', cursor: 'pointer' });
            //    o.unbind('click');
            //    if (target.nodeName == "IMG") {
            //        o.unbind('click');
            //        return false;
            //    } else {
            //        o.on('click', function() {
            //            var url = $(this).attr('link');
            //            location.href = url;
            //        });
            //    }
            //});
        });
    </script>

}
 

